<template>
  <view class="body">
    <view class="progress">
      <view v-if="state.questionList.length > 0" class="model-name">
        {{ state.questionList[state.tabActive].name }}
      </view>
      <up-line-progress
        :percentage="100 * (current / total) || 0"
        activeColor="#00d1b6"
        inactiveColor="#f5f5f5"
        :showText="false"
        height="8"
      ></up-line-progress>
    </view>
    <view v-if="!state.isSelect" class="wrap">
      <view class="tips">请根据实际情况，选择最符合的一项</view>
      <!-- <view class="questionName">请选择体检用户</view> -->
      <my-question
        style="margin-top: 32rpx"
        :cId="cId"
        :cWidth="cWidth"
        :List="state.questionList[Number(state.tabActive)]?.list"
        @change="onChange"
      />
    </view>

    <view class="fixed">
      <view v-if="state.tabActive == 0 && state.questionActive == 0"></view>
      <button v-else class="pre_btn" @tap="prev()">上一题</button>
      <button class="next_btn" @tap="nextClick()">
        {{
          state.tabActive + 1 == state.questionList.length &&
          state.questionActive + 1 == state.questionList[state.tabActive].list.length
            ? '提交问卷'
            : '下一题'
        }}
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, computed, nextTick, watch } from 'vue'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { debounce, throttle, deepCopy, parseTime, typeOf } from '@/utils/tools'
import { query_patient } from '@/api/family'
import { base_info } from '@/api/moreMessage'
import { search_food } from '@/api/food'
import { get_new_weight, hasSportsPlan } from '@/module/api/sports'
import { new_question, weight_save, question_rewrite } from '@/module/api/questionaire'
import { formatDate } from '@/utils/util'
import store from '@/store'
import MyQuestion from '@/module/components/MyQuestion/single.vue'
import {
  showCondition,
  next,
  validate,
  convert,
  fillValue
} from '@/module/components/MyQuestion/tools'
import { questionnaire_get } from '../api'

const state = reactive({
  tabActive: 0, // 模块下标
  questionActive: 0, // 题目下标
  isSelect: false,
  userList: [],
  questionList: [],
  questionInfo: {},
  searchFocus: false,
  isSearch: false,
  searchValue: '',
  searchHistory: [],
  searchList: [],
  searchResults: []
})
const userInfo = ref({})
const chooseInfo = ref({})
const originList = ref([])
const searchShow = ref(false)
const questionState = ref(false)

let currentId = ''
const scrollTop = ref(0)
const oldScrollTop = ref(0)
const cWidth = ref(uni.upx2px(750 - 192))
const listOld = ref([])
const questionListAfter = ref([])
const cId = ref('')
const isFinish = ref(false)

const total = computed(() => {
  let num = 0
  state.questionList.forEach((item: any) => {
    item.list.forEach((val: any) => {
      num++
    })
  })
  return num
})

const current = computed(() => {
  let num = 0
  state.questionList.forEach((item: any, index: number) => {
    item.list.forEach((val: any, idx: number) => {
      if (index + 1 < state.questionList.length || idx < item.list.length) {
        if (val.value != '' || val.inputText != '' || val.value.length > 0) {
          num++
        }
      }
    })
  })
  return num
})
onLoad(() => {
  questionState.value = false
  userInfo.value = JSON.parse(uni.getStorageSync('userInfo'))
  chooseInfo.value = userInfo.value.patientInfo
  wx.enableAlertBeforeUnload({
    message: '确认要退出吗？您填写的内容未提交',
    success: function (res) {
      console.log('成功', res)
    },
    fail: function (errMsg) {
      console.log('失败', errMsg)
    }
  })
  init()
})
onUnload(() => {
  if (questionState.value == false) {
    uni.navigateTo({ url: '/module/src/pages/sports/sportsQuestionnaire/back' })
  } else {
    questionState.value = false
  }
})
watch(
  () => state.questionActive,
  () => {
    scrollTop.value = oldScrollTop.value
    nextTick(() => {
      scrollTop.value = 0
    })
  }
)

const init = () => {
  const params = { questionnaireKey: 'week_feedback_questionnaire' }
  questionnaire_get(params).then((res) => {
    originList.value = JSON.parse(res.data.content)
    let convertList = convert(originList.value)
    listOld.value = convertList
    state.questionList = showCondition(convertList)
    state.questionInfo = res.data
    cId.value = state.questionList[0].list[0].id
    state.isSelect = false
  })
}

const onChange = () => {
  state.questionList = showCondition(listOld.value)
}

const prev = () => {
  const result = next(state.questionList, cId.value)
  cId.value = result.before.id

  if (state.questionActive == 0) {
    state.tabActive--
    state.questionActive = state.questionList[state.tabActive].list.length - 1
  } else {
    state.questionActive--
  }
}
const nextClick = throttle(() => {
  // uni.navigateTo({
  //   url: '/module/src/pages/sports/sportsQuestionnaire/feedbackResult?type=todayFeedback'
  // })
  let questionArray = state.questionList[Number(state.tabActive)].list.filter(
    (item) => item.id === cId.value
  )
  let f = List_validate(questionArray)
  if (f) {
    checkNext()
    console.log('校验通过')
  } else {
    console.log('校验失败')
  }
}, 300)
const List_validate = (list) => {
  const List = list
  const arr = []
  List.map((u) => {
    const v = validate(u)
    arr.push(v)
  })
  arr.map((v) => {
    v.item['validate'] = v.code
    if (v.code) {
      v.item['validate_message'] = v.message
    } else {
      v.item['validate_message'] = ''
    }
  })
  const f = arr.find((v) => {
    return v.code
  })
  if (f) {
    return false
  } else {
    return true
  }
}
const checkNext = () => {
  if (
    state.tabActive + 1 == state.questionList.length &&
    state.questionActive + 1 == state.questionList[state.tabActive].list.length
  ) {
    confirm()
  } else {
    if (state.questionActive + 1 == state.questionList[state.tabActive].list.length) {
      if (state.tabActive == state.questionList.length) {
        state.questionActive++
        isFinish.value = true
      } else {
        state.questionActive = 0
        state.tabActive++
      }
      let result = next(state.questionList, cId.value)
      cId.value = result.next.id
    } else {
      state.questionActive++
      let result = next(state.questionList, cId.value)
      cId.value = result.next.id
    }
  }
}
const confirm = () => {
  const params = {
    questionnaireKey: 'week_feedback_questionnaire',
    patientQuestionnaireAnswerVOs: []
  }
  state.questionList.forEach((item: any) => {
    item.list.forEach((val: any) => {
      const answerModel = {
        userId: userInfo.value.userId,
        empi: userInfo.value.patientInfo.empi,
        questionId: val.id,
        questionnaireId: state.questionInfo.questionnaireId,
        relationQuestionCode: val.relationQuestionCode,
        optionId: '',
        content: '',
        extContent: val.type == '选择 + 输入' ? val.inputText : '',
        score: val.score || 0
        // sort: val.sort || ''
      }
      if ((val.type == '单选' && val.value) || (val.type == '输入' && val.value)) {
        const answer = {
          ...answerModel,
          optionId: val.type == '单选' && val.optionId ? String(val.optionId) : '',
          content: val.value
        }
        params.patientQuestionnaireAnswerVOs.push(answer)
      } else if (val.type == '多选' && val.value && val.value.length > 0) {
        val.optionId = val.options
          .filter((item) => val.sort.includes(item.sort))
          .map((item) => item.id)
        val.score = val.options
          .filter((item) => val.sort.includes(item.sort))
          .map((item) => item.score)
        val.value.forEach((i: string, idx: number) => {
          const answer = {
            ...answerModel,
            optionId: val.optionId[idx] + '',
            content: i,
            score: val.score[idx]
          }
          params.patientQuestionnaireAnswerVOs.push(answer)
        })
      } else {
        if (val.value) {
          const answer = {
            ...answerModel,
            optionId: '',
            content: val.value
          }
          params.patientQuestionnaireAnswerVOs.push(answer)
        }
      }
    })
  })
  uni.showLoading({
    title: '正在提交问卷',
    mask: true
  })
  weight_save(params).then((res) => {
    if (res.code == 0) {
      let params = {
        userId: userInfo.value.userId,
        empi: userInfo.value.patientInfo.empi
      }
      base_info(params).then((res) => {
        userInfo.value.patientInfo = res.data
        userInfo.value.patientInfo.sportQuestionState = true
        store.commit('SET_USERINFO', userInfo.value)
        uni.hideLoading()
        uni.showToast({
          title: '问卷提交成功',
          icon: 'none',
          duration: 2000,
          success: () => {
            questionState.value = true
            setTimeout(() => {
              uni.redirectTo({
                url: '/module/src/pages/sports/sportsQuestionnaire/feedbackResult?type=feedback'
              })
            }, 2000)
          }
        })
      })
    }
  })
}

const scroll = (e: any) => {
  oldScrollTop.value = e.target.scrollTop
}
</script>

<style lang="scss" scoped>
.body {
  min-height: calc(100vh - 120rpx - constant(safe-area-inset-bottom));
  min-height: calc(100vh - 120rpx - env(safe-area-inset-bottom));
  padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
  .progress {
    padding: 24rpx 32rpx;
    background: #fff;
    .model-name {
      font-weight: 600;
      font-size: 40rpx;
      color: #222222;
      margin-bottom: 16rpx;
    }
  }
  .wrap {
    margin: 32rpx;
    padding: 32rpx;
    max-height: calc(100vh - 380rpx);
    background: #ffffff;
    border-radius: 16rpx;
    // overflow-y: scroll;
    .scroll-Y {
      position: relative;
      max-height: calc(100vh - 444rpx);
      overflow-y: scroll;
    }
    .tips {
      font-weight: 400;
      font-size: 28rpx;
      color: #999999;
    }
    .questionName {
      font-weight: 500;
      font-size: 36rpx;
      color: #222222;
      padding-top: 16rpx;
      .tag {
        display: inline-block;
        height: 40rpx;
        padding: 0 16rpx;
        margin-left: 8rpx;
        font-size: 24rpx;
        font-weight: 500;
        line-height: 40rpx;
        color: #fff;
        text-align: center;
        background: #5c8eff;
        border-radius: 4rpx;
        transform: translateY(-4rpx);
      }
    }
    .tips {
      font-weight: 400;
      font-size: 28rpx;
      color: #999999;
      margin-top: 8rpx;
    }
    .selects {
      margin-top: 32rpx;
      padding-bottom: 4rpx;
      border-top: 2rpx dashed #cfcfcf;
      border-spacing: 4rpx 4rpx;
    }
    .items {
      background: #fafafa;
      box-sizing: border-box;
      border-radius: 8rpx;
      font-weight: 400;
      font-size: 30rpx;
      color: #222222;
      padding: 24rpx 30rpx 22rpx;
      border: 1rpx solid transparent;
      margin-top: 32rpx;
      display: flex;
      justify-content: flex-start;
      .item-name {
        font-weight: 500;
        font-size: 32rpx;
        color: #222222;
      }
      .info-tag {
        display: inline-block;
        height: 48rpx;
        line-height: 48rpx;
        padding: 0 24rpx;
        margin-left: 32rpx;
        background: #ffffff;
        border-radius: 4rpx;
        border: 1rpx solid #e5e6eb;
        font-weight: 400;
        font-size: 24rpx;
        color: #666666;
        transform: rotateZ(360deg);
      }
    }
    .active {
      color: #00d1b6;
      background: rgba(0, 209, 182, 0.05);
      font-weight: 700;
      border: 1rpx solid #00d1b6;
      transform: rotateZ(360deg);
    }
    .type_input {
      height: 108rpx;
      line-height: 108rpx;
      border: none;
      border-bottom: 2rpx solid #222;
    }
    .search-input {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      width: 100%;
      height: 84rpx;
      padding: 22rpx 24rpx;
      margin-top: 24rpx;
      font-size: 30rpx;
      font-weight: 400;
      line-height: 84rpx;
      color: #999;
      background: #fff;
      border: 2rpx solid #000;
      border-radius: 48rpx;
    }

    .allergy-foods {
      height: 560rpx;
      margin-top: 24rpx;
      overflow: auto;

      .food-list {
        display: flex;
        flex-wrap: wrap;
        gap: 24rpx;
        justify-content: left;

        .foods-item {
          display: flex;
          align-items: center;
          height: 64rpx;
          padding: 0 16rpx;
          font-size: 28rpx;
          font-weight: 400;
          color: #00d1b6;
          background: rgb(0 209 182 / 10%);
          border-radius: 4rpx;
        }
      }
    }
  }

  .search-body {
    // 搜索弹窗
    width: 100vw;
    height: calc(100vh - 160rpx);

    .title {
      height: 108rpx;
      font-size: 32rpx;
      font-weight: 700;
      line-height: 108rpx;
      color: #222;
      text-align: center;
      border-bottom: 1rpx solid #e5e6eb;
    }

    .search-bar {
      padding: 24rpx 32rpx;
    }

    .search_content {
      // height: calc(100vh - 596rpx);
      background: #fff;

      .search_history {
        margin: 0 32rpx;

        .history_top {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20rpx;

          .title {
            font-size: 30rpx;
            font-weight: 700;
            color: #333;
          }

          .img_del {
            width: 40rpx;
            height: 40rpx;
            font-size: 40rpx;
            color: #999;
          }
        }

        .history_content {
          display: flex;
          flex-wrap: wrap;
          gap: 20rpx;
          justify-content: flex-start;

          .history_item {
            padding: 10rpx 30rpx;
            font-size: 26rpx;
            font-weight: 400;
            color: #666;
            background: #fafafa;
            border-radius: 30rpx;
          }
        }
      }

      .nodata {
        text-align: center;

        .img_nodata {
          width: 320rpx;
          height: 240rpx;
          margin-top: 222rpx;
        }

        .nodata_text {
          font-size: 28rpx;
          font-weight: 400;
          color: #666;
        }
      }
      .scroll_view_style {
        height: calc(100vh - 524rpx);
        overflow: auto;
      }
      .search_list {
        background: #fff;

        .search_item {
          position: relative;
          box-sizing: border-box;
          height: 108rpx;
          padding: 34rpx 32rpx;
          border-bottom: 1rpx solid #e5e6eb;

          .name {
            font-size: 30rpx;
            font-weight: 500;
            color: #222;
          }

          .img_right {
            position: absolute;
            top: 50%;
            right: 32rpx;
            width: 40rpx;
            height: 40rpx;
            margin-top: -20rpx;
          }
        }
      }
    }

    .popbtn {
      width: 100%;
    }
  }

  .fixed {
    position: fixed;
    width: 100%;
    bottom: 0;
    left: 0;
    z-index: 10;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    box-sizing: border-box;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    gap: 24rpx;
    .pre_btn {
      background: #ffffff;
      width: 100%;
      border-radius: 44rpx;
      font-weight: 500;
      font-size: 32rpx;
      border: 1rpx solid #00d1b6;
      color: #00d1b6;
    }
    .next_btn {
      width: 100%;
      background: #00d1b6;
      border-radius: 44rpx;
      font-weight: 500;
      font-size: 32rpx;
      color: #ffffff;
    }
  }
  ::v-deep .u-modal__title {
    font-weight: 500 !important;
    font-size: 34rpx !important;
    color: #222222 !important;
  }
}

:v-deep .u-search {
  padding: 10px;
}

::v-deep .u-search__content__input--placeholder {
  font-size: 30rpx !important;
  color: #999 !important;
}

::v-deep .u-search__content {
  justify-content: flex-start;
  height: 80rpx !important;
  padding: 20rpx 24rpx !important;
  background-color: #fff !important;
  border: 2rpx solid #000;
  border-radius: 40rpx !important;
  border-color: #000 !important;
}

::v-deep .u-search__content__icon {
  padding: 0 !important;

  .u-icon .u-icon__icon {
    color: #000 !important;
  }
}

::v-deep .u-search__content__input {
  font-size: 30rpx !important;
  background-color: #fff !important;
}

::v-deep .u-search__action {
  font-size: 30rpx !important;
  font-weight: 500;
  line-height: 80rpx !important;
  color: #00d1b6 !important;
}

::v-deep .u-icon__icon {
  font-size: 44rpx !important;
  line-height: 50rpx !important;
}
</style>
